//
//  CNDataCommunication.m
//  EkeyPropoganda
//
//  Created by mal on 15/4/21.
//  Copyright (c) 2015年 cnsoft. All rights reserved.
//

#import "BIDDataCommunication.h"
#import "BIDGlobalMethods.h"

@interface BIDDataCommunication()<NSURLConnectionDataDelegate>
{
    NSURL *_url;
    NSMutableURLRequest *_urlRequest;
    NSURLConnection *_urlConnection;
    NSMutableData *_data;
}
@end

@implementation BIDDataCommunication
@synthesize delegate;
@synthesize completionHandler;
@synthesize requestType;

+ (BIDDataCommunication*)getInstance
{
    static dispatch_once_t token;
    static BIDDataCommunication *dataCommunication;
    dispatch_once(&token, ^{
        dataCommunication = [[BIDDataCommunication alloc] init];
        //默认为HttpService
        dataCommunication.requestType = HTTP_SERVICE;
    });
    return dataCommunication;
}

+ (int)getDataFromNet:(NSString *)strURL data:(NSMutableData *)desData
{
    NSURL *url;
    NSURLRequest *urlRequest;
    NSURLResponse *response;
    NSError *err;
    NSData *data;
    url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    urlRequest = [[NSURLRequest alloc] initWithURL:url];
    //
    data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&err];
    if(data!=nil && err==nil)
    {
        [desData appendData:data];
        return 1;
    }
    return 0;
}

+ (int)getDataWithURL:(NSString *)strURL andPost:(NSString*)postData toDictionary:(NSMutableDictionary *)desDictionary
{
    NSURL *url;
    NSMutableURLRequest *urlRequest;
    NSURLResponse *response;
    NSError *err;
    NSData *data;
    url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    //
    NSData *post_data = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postLength = [[NSString alloc] initWithFormat:@"%lu", (unsigned long)post_data.length];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setHTTPBody:post_data];
    //
    data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&err];
    if(err)
    {
        NSLog(@"%@", [err localizedDescription]);
    }
    if(!err && data)
    {
        id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
        if(obj!=nil && err==nil)
        {
            if([obj isKindOfClass:[NSArray class]])
            {
            }
            else if([obj isKindOfClass:[NSDictionary class]])
            {
                [desDictionary setDictionary:obj];
            }
            return 1;
        }
        else
        {
            return 0;
        }
    }
    return 0;
}

- (id)initWithURL:(NSString *)strURL
{
    self = [super init];
    if(self)
    {
        _url = [NSURL URLWithString:strURL];
        _urlRequest = [NSMutableURLRequest requestWithURL:_url];
        _urlConnection = [[NSURLConnection alloc] initWithRequest:_urlRequest delegate:self];
    }
    return self;
}

- (NSURLConnection*)getDataFromNet:(NSString*)strURL postValue:(NSString*)postValue completionHandler:(void (^)(id obj, NSError* err))completionHandler1
{
    if(!_data)
    {
        _data = [[NSMutableData alloc] init];
    }
    else
    {
        _data.length = 0;
    }
    self.completionHandler = completionHandler1;
    NSData *postData = [postValue dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postLength = [[NSString alloc] initWithFormat:@"%lu", (unsigned long)postData.length];
    _url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    _urlRequest = [NSMutableURLRequest requestWithURL:_url];
    [_urlRequest setHTTPMethod:@"POST"];
    if(requestType == WEB_SERVICE)
    {
        [_urlRequest setValue:@"text/xml;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    }
    else
    {
        [_urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    }
    [_urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [_urlRequest setHTTPBody:postData];
    _urlConnection = [[NSURLConnection alloc] initWithRequest:_urlRequest delegate:self];
    return _urlConnection;
}
#pragma mark - Static
+ (id)getDataFromNetBySyn:(NSString*)strURL postValue:(NSString*)postValue
{
    NSURL *url;
    NSMutableURLRequest *urlRequest;
    NSURLResponse *response = nil;
    NSError *err = nil;
    NSData *data = nil;
    NSData *postData = [postValue dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postLength = [[NSString alloc] initWithFormat:@"%lu", (unsigned long)postData.length];
    url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setHTTPBody:postData];
    data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&err];
    if(data!=nil && err==nil)
    {
        id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
        if(obj!=nil && err==nil)
        {
            return obj;
        }
    }
    return nil;
}

#pragma mark -NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //NSDictionary *headers = [(NSHTTPURLResponse*)response allHeaderFields];
    //NSString *strCookies = [headers objectForKey:@"Set-Cookie"];
    //NSLog(@"%@", strCookies);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if(_data&&_data.length>0)
    {
        NSError *err;
        id obj = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingAllowFragments error:&err];
        self.completionHandler(obj, err);
    }
    else
    {
        self.completionHandler(nil, nil);
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.completionHandler(nil, error);    
}


@end
